//! # 性能配置管理
//! 
//! 提供性能优化相关的配置定义和管理功能。
//! 支持连接池、内存管理、异步任务池等组件的灵活配置。

use serde::{Deserialize, Serialize};
use std::time::Duration;
use rustcloud_core::config_builder::{ConnectionPoolConfig, ConfigFactory};

/// 性能配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// 连接池配置（使用统一的配置）
    pub connection_pool: ConnectionPoolConfig,
    
    /// 线程池配置
    pub thread_pool: ThreadPoolConfig,
    
    /// 内存配置
    pub memory: MemoryConfig,
    
    /// 异步任务池配置
    pub async_task_pool: AsyncTaskPoolConfig,
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            // 使用统一的配置工厂创建连接池配置
            connection_pool: ConfigFactory::create_dev_connection_pool(),
            thread_pool: ThreadPoolConfig::default(),
            memory: MemoryConfig::default(),
            async_task_pool: AsyncTaskPoolConfig::default(),
        }
    }
}

/// 连接池配置（重新导出统一配置，保持向后兼容）
pub use rustcloud_core::config_builder::ConnectionPoolConfig as UnifiedConnectionPoolConfig;

/// 为了保持向后兼容，提供原有的 ConnectionPoolConfig 类型别名
pub type ConnectionPoolConfig = UnifiedConnectionPoolConfig;

/// 线程池配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadPoolConfig {
    /// 核心线程数
    pub core_threads: u32,
    
    /// 最大线程数
    pub max_threads: u32,
    
    /// 线程空闲超时（秒）
    pub thread_idle_timeout_seconds: u64,
    
    /// 队列大小
    pub queue_size: usize,
}

impl Default for ThreadPoolConfig {
    fn default() -> Self {
        Self {
            core_threads: num_cpus::get() as u32,
            max_threads: (num_cpus::get() * 2) as u32,
            thread_idle_timeout_seconds: 60,
            queue_size: 1000,
        }
    }
}

impl ThreadPoolConfig {
    /// 获取线程空闲超时Duration
    pub fn thread_idle_timeout(&self) -> Duration {
        Duration::from_secs(self.thread_idle_timeout_seconds)
    }
    
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.core_threads == 0 {
            return Err("核心线程数必须大于0".to_string());
        }
        
        if self.max_threads < self.core_threads {
            return Err("最大线程数不能小于核心线程数".to_string());
        }
        
        if self.queue_size == 0 {
            return Err("队列大小必须大于0".to_string());
        }
        
        Ok(())
    }
}

/// 内存配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// 是否启用内存池
    pub pooling_enabled: bool,
    
    /// 默认块大小（字节）
    pub default_block_size: usize,
    
    /// 最大内存池数量
    pub max_pools: usize,
    
    /// 每个池的最大块数
    pub max_blocks_per_pool: usize,
    
    /// 垃圾回收配置
    pub gc: GcConfig,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            pooling_enabled: true,
            default_block_size: 1024,
            max_pools: 10,
            max_blocks_per_pool: 1000,
            gc: GcConfig::default(),
        }
    }
}

impl MemoryConfig {
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.default_block_size == 0 {
            return Err("默认块大小必须大于0".to_string());
        }
        
        if self.max_pools == 0 {
            return Err("最大内存池数量必须大于0".to_string());
        }
        
        if self.max_blocks_per_pool == 0 {
            return Err("每个池的最大块数必须大于0".to_string());
        }
        
        self.gc.validate()?;
        
        Ok(())
    }
}

/// 垃圾回收配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GcConfig {
    /// 是否启用自动GC
    pub auto_gc_enabled: bool,
    
    /// GC阈值（使用率）
    pub gc_threshold: f64,
    
    /// GC间隔（秒）
    pub gc_interval_seconds: u64,
    
    /// 强制GC的内存压力阈值
    pub pressure_threshold: f64,
}

impl Default for GcConfig {
    fn default() -> Self {
        Self {
            auto_gc_enabled: true,
            gc_threshold: 0.8,
            gc_interval_seconds: 30,
            pressure_threshold: 0.9,
        }
    }
}

impl GcConfig {
    /// 获取GC间隔Duration
    pub fn gc_interval(&self) -> Duration {
        Duration::from_secs(self.gc_interval_seconds)
    }
    
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.gc_threshold <= 0.0 || self.gc_threshold >= 1.0 {
            return Err("GC阈值必须在0.0到1.0之间".to_string());
        }
        
        if self.pressure_threshold <= 0.0 || self.pressure_threshold >= 1.0 {
            return Err("内存压力阈值必须在0.0到1.0之间".to_string());
        }
        
        if self.pressure_threshold <= self.gc_threshold {
            return Err("内存压力阈值必须大于GC阈值".to_string());
        }
        
        if self.gc_interval_seconds == 0 {
            return Err("GC间隔必须大于0".to_string());
        }
        
        Ok(())
    }
}

/// 异步任务池配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AsyncTaskPoolConfig {
    /// 工作线程数
    pub worker_threads: usize,
    
    /// 任务队列大小
    pub queue_size: usize,
    
    /// 是否启用任务统计
    pub stats_enabled: bool,
}

impl Default for AsyncTaskPoolConfig {
    fn default() -> Self {
        Self {
            worker_threads: num_cpus::get(),
            queue_size: 10000,
            stats_enabled: true,
        }
    }
}

impl AsyncTaskPoolConfig {
    /// 验证配置的有效性
    pub fn validate(&self) -> Result<(), String> {
        if self.worker_threads == 0 {
            return Err("工作线程数必须大于0".to_string());
        }
        
        if self.queue_size == 0 {
            return Err("任务队列大小必须大于0".to_string());
        }
        
        Ok(())
    }
}

/// 性能配置构建器
pub struct PerformanceConfigBuilder {
    config: PerformanceConfig,
}

impl PerformanceConfigBuilder {
    /// 创建新的构建器
    pub fn new() -> Self {
        Self {
            config: PerformanceConfig::default(),
        }
    }

    /// 设置连接池最大连接数
    pub fn max_connections(mut self, max_connections: u32) -> Self {
        self.config.connection_pool.max_connections = max_connections;
        self
    }

    /// 设置连接池最小连接数
    pub fn min_connections(mut self, min_connections: u32) -> Self {
        self.config.connection_pool.min_connections = min_connections;
        self
    }

    /// 设置连接超时时间（秒）
    pub fn connection_timeout(mut self, seconds: u64) -> Self {
        self.config.connection_pool.connection_timeout_seconds = seconds;
        self
    }

    /// 设置空闲超时时间（秒）
    pub fn idle_timeout(mut self, seconds: u64) -> Self {
        self.config.connection_pool.idle_timeout_seconds = seconds;
        self
    }

    /// 启用或禁用连接验证
    pub fn validation_enabled(mut self, enabled: bool) -> Self {
        self.config.connection_pool.validation_enabled = enabled;
        self
    }

    /// 设置核心线程数
    pub fn core_threads(mut self, core_threads: u32) -> Self {
        self.config.thread_pool.core_threads = core_threads;
        self
    }

    /// 设置最大线程数
    pub fn max_threads(mut self, max_threads: u32) -> Self {
        self.config.thread_pool.max_threads = max_threads;
        self
    }

    /// 设置线程空闲超时时间（秒）
    pub fn thread_idle_timeout(mut self, seconds: u64) -> Self {
        self.config.thread_pool.thread_idle_timeout_seconds = seconds;
        self
    }

    /// 设置队列大小
    pub fn queue_size(mut self, queue_size: usize) -> Self {
        self.config.thread_pool.queue_size = queue_size;
        self
    }

    /// 启用或禁用内存池
    pub fn memory_pooling_enabled(mut self, enabled: bool) -> Self {
        self.config.memory.pooling_enabled = enabled;
        self
    }

    /// 设置默认块大小（字节）
    pub fn default_block_size(mut self, block_size: usize) -> Self {
        self.config.memory.default_block_size = block_size;
        self
    }

    /// 设置最大内存池数量
    pub fn max_pools(mut self, max_pools: usize) -> Self {
        self.config.memory.max_pools = max_pools;
        self
    }

    /// 设置每个池的最大块数
    pub fn max_blocks_per_pool(mut self, max_blocks: usize) -> Self {
        self.config.memory.max_blocks_per_pool = max_blocks;
        self
    }

    /// 启用或禁用自动GC
    pub fn auto_gc_enabled(mut self, enabled: bool) -> Self {
        self.config.memory.gc.auto_gc_enabled = enabled;
        self
    }

    /// 设置GC阈值
    pub fn gc_threshold(mut self, threshold: f64) -> Self {
        self.config.memory.gc.gc_threshold = threshold;
        self
    }

    /// 设置GC间隔（秒）
    pub fn gc_interval(mut self, seconds: u64) -> Self {
        self.config.memory.gc.gc_interval_seconds = seconds;
        self
    }

    /// 设置内存压力阈值
    pub fn pressure_threshold(mut self, threshold: f64) -> Self {
        self.config.memory.gc.pressure_threshold = threshold;
        self
    }

    /// 设置异步任务池工作线程数
    pub fn async_worker_threads(mut self, worker_threads: usize) -> Self {
        self.config.async_task_pool.worker_threads = worker_threads;
        self
    }

    /// 设置异步任务队列大小
    pub fn async_queue_size(mut self, queue_size: usize) -> Self {
        self.config.async_task_pool.queue_size = queue_size;
        self
    }

    /// 启用或禁用任务统计
    pub fn async_stats_enabled(mut self, enabled: bool) -> Self {
        self.config.async_task_pool.stats_enabled = enabled;
        self
    }

    /// 构建性能配置
    pub fn build(self) -> Result<PerformanceConfig, String> {
        // 验证所有配置
        self.config.connection_pool.validate()?;
        self.config.thread_pool.validate()?;
        self.config.memory.validate()?;
        self.config.async_task_pool.validate()?;
        
        Ok(self.config)
    }
}

impl Default for PerformanceConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = PerformanceConfig::default();
        
        // 验证连接池配置
        assert_eq!(config.connection_pool.max_connections, 100);
        assert_eq!(config.connection_pool.min_connections, 10);
        assert_eq!(config.connection_pool.connection_timeout_seconds, 30);
        
        // 验证线程池配置
        assert_eq!(config.thread_pool.core_threads, num_cpus::get() as u32);
        assert_eq!(config.thread_pool.max_threads, (num_cpus::get() * 2) as u32);
        
        // 验证内存配置
        assert!(config.memory.pooling_enabled);
        assert_eq!(config.memory.default_block_size, 1024);
        
        // 验证异步任务池配置
        assert_eq!(config.async_task_pool.worker_threads, num_cpus::get());
    }

    #[test]
    fn test_config_validation() {
        // 测试有效的配置
        let valid_config = ConnectionPoolConfig {
            max_connections: 100,
            min_connections: 10,
            connection_timeout_seconds: 30,
            idle_timeout_seconds: 300,
            validation_interval_seconds: 60,
            validation_enabled: true,
        };
        assert!(valid_config.validate().is_ok());
        
        // 测试无效的配置 - 最大连接数为0
        let invalid_config = ConnectionPoolConfig {
            max_connections: 0,
            ..valid_config.clone()
        };
        assert!(invalid_config.validate().is_err());
        
        // 测试无效的配置 - 最小连接数大于最大连接数
        let invalid_config = ConnectionPoolConfig {
            min_connections: 150,
            max_connections: 100,
            ..valid_config.clone()
        };
        assert!(invalid_config.validate().is_err());
        
        // 测试无效的配置 - 连接超时为0
        let invalid_config = ConnectionPoolConfig {
            connection_timeout_seconds: 0,
            ..valid_config.clone()
        };
        assert!(invalid_config.validate().is_err());
    }

    #[test]
    fn test_config_builder() {
        let config = PerformanceConfigBuilder::new()
            .max_connections(200)
            .min_connections(20)
            .connection_timeout(60)
            .core_threads(8)
            .max_threads(16)
            .default_block_size(2048)
            .auto_gc_enabled(false)
            .async_worker_threads(8)
            .build()
            .unwrap();
            
        assert_eq!(config.connection_pool.max_connections, 200);
        assert_eq!(config.connection_pool.min_connections, 20);
        assert_eq!(config.connection_pool.connection_timeout_seconds, 60);
        assert_eq!(config.thread_pool.core_threads, 8);
        assert_eq!(config.thread_pool.max_threads, 16);
        assert_eq!(config.memory.default_block_size, 2048);
        assert!(!config.memory.gc.auto_gc_enabled);
        assert_eq!(config.async_task_pool.worker_threads, 8);
    }

    #[test]
    fn test_gc_config_validation() {
        // 测试有效的GC配置
        let valid_gc_config = GcConfig::default();
        assert!(valid_gc_config.validate().is_ok());
        
        // 测试无效的GC配置 - 阈值超出范围
        let invalid_gc_config = GcConfig {
            gc_threshold: 1.5,
            ..valid_gc_config.clone()
        };
        assert!(invalid_gc_config.validate().is_err());
        
        // 测试无效的GC配置 - 压力阈值小于GC阈值
        let invalid_gc_config = GcConfig {
            gc_threshold: 0.8,
            pressure_threshold: 0.7,
            ..valid_gc_config.clone()
        };
        assert!(invalid_gc_config.validate().is_err());
        
        // 测试无效的GC配置 - 间隔为0
        let invalid_gc_config = GcConfig {
            gc_interval_seconds: 0,
            ..valid_gc_config.clone()
        };
        assert!(invalid_gc_config.validate().is_err());
    }

    #[test]
    fn test_duration_helpers() {
        let config = ConnectionPoolConfig::default();
        assert_eq!(config.connection_timeout(), Duration::from_secs(30));
        assert_eq!(config.idle_timeout(), Duration::from_secs(300));
        assert_eq!(config.validation_interval(), Duration::from_secs(60));
        
        let gc_config = GcConfig::default();
        assert_eq!(gc_config.gc_interval(), Duration::from_secs(30));
    }
}